<script setup>
import { useAppStore, useWMTSStore } from '@/stores'
import ExceptionLogger from '@/utils/errorHandler'
import { useBoolean } from '@/hooks/useBoolean'
import proj4 from 'proj4'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import WMTS from 'ol/source/WMTS'
import Projection from 'ol/proj/Projection'
import WMTSTileGrid from 'ol/tilegrid/WMTS'

const appStore = useAppStore()
const wmtsStore = useWMTSStore()
const selectedValue = ref('')
const wmtsURL = ref('')
const windowWidth = ref(window.innerWidth)
const windowHeight = ref(window.innerHeight)
const adaptHeight = appStore.showTabs ? (appStore.showFooter ? ref(387) : ref(427)) : appStore.showFooter ? ref(427) : ref(472)
const options = ref([])
const loading = ref(false)
const { bool: addLoading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)
const computedHeight = computed(() => windowHeight.value - adaptHeight.value)

const handleResize = () => {
  windowWidth.value = window.innerWidth
  windowHeight.value = window.innerHeight
}

const handleUpdateValue = async (_, option) => {
  startLoading()
  try {
    wmtsStore.setCurrentTileMatrixSet(option.label)
    await wmtsStore.setOpenlayersAddCode()
    if (window.olMap_wmts) {
      window.olMap_wmts.setTarget(null)
      window.olMap_wmts = null
    }
    eval(wmtsStore.openlayersAddCode)
  } catch (error) {
    ExceptionLogger.wmtsHandleException(error)
  } finally {
    endLoading()
  }
}

const load = async () => {
  if (!ExceptionLogger.isValidURL(wmtsURL.value)) return ExceptionLogger.logException('请输入正确的 URL 地址')
  loading.value = true
  startLoading()
  try {
    await wmtsStore.initWMTSInfo(wmtsURL.value)
    await wmtsStore.setOpenlayersAddCode()
    if (window.olMap_wmts) {
      window.olMap_wmts.setTarget(null)
      window.olMap_wmts = null
    }
    eval(wmtsStore.openlayersAddCode)
  } catch (error) {
    ExceptionLogger.wmtsHandleException(error)
  } finally {
    loading.value = false
    endLoading()
  }
}

// 初始化地图
function initMap() {
  proj4.defs('EPSG:3857', '+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs')
  window.olMap_wmts = new Map({
    target: document.getElementById('olMap_wmts'),
    view: new View({
      projection: new Projection({
        code: 'EPSG:3857',
        extent: [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244],
        units: 'm',
        global: true
      }),
      multiWorld: true
    })
  })
  const wmtsLayer = new TileLayer({
    source: new WMTS({
      url: 'https://iserver.supermap.io/iserver/services/map-china400/wmts100',
      layer: 'China',
      matrixSet: 'Custom_China',
      format: 'image/png',
      tileGrid: new WMTSTileGrid({
        origin: [-2.0037508342787e7, 2.0037508342787e7],
        resolutions: [156543.0339280409, 78271.51696402059, 39135.75848201029, 19567.879241005117, 9783.939620502559, 4891.969810251267, 2445.9849051256388, 1222.9924525628205, 611.4962262814089, 305.7481131407058, 152.87405657035234, 76.43702828517617, 38.218514142588226],
        matrixIds: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
      }),
      style: 'default'
    })
  })
  olMap_wmts.addLayer(wmtsLayer)
  olMap_wmts.getView().fit([-2.0037508342789248e7, -2.003750834278914e7, 2.0037508342789244e7, 2.0037508342789087e7])
}

onMounted(async () => {
  window.addEventListener('resize', handleResize)
  initMap()
})

onUnmounted(() => window.removeEventListener('resize', handleResize))

watch(
  () => wmtsStore.wmtsInfo.mapLayer,
  () => {
    if (Array.isArray(wmtsStore.wmtsInfo.mapLayer) && wmtsStore.wmtsInfo.mapLayer.length != 0) {
      options.value = wmtsStore.wmtsInfo.mapLayer.map((item) => {
        return {
          label: item.Title,
          key: item.Identifier,
          children: item.TileMatrixSet.map((matrix) => ({
            label: matrix.TileMatrixSetName,
            key: matrix.TileMatrixSetName
          }))
        }
      })
      selectedValue.value = options.value[0].children[0].label
    }
  }
)
watch(
  () => appStore.showTabs,
  () => (appStore.showTabs ? (adaptHeight.value += 45) : (adaptHeight.value -= 45)),
  { immediate: true }
)
watch(
  () => appStore.showFooter,
  () => (appStore.showFooter ? (adaptHeight.value += 40) : (adaptHeight.value -= 40)),
  { immediate: true }
)
</script>

<template>
  <n-card class="flex-1">
    <n-grid :x-gap="0" :y-gap="8" :cols="2">
      <n-gi>
        <n-flex>
          <n-input-group>
            <n-input v-model:value="wmtsURL" placeholder="请输入WMTS能力文档地址" />
            <n-button type="primary" :loading="loading" @click="load">
              <template #icon>
                <icon-park-outline-loading />
              </template>
              加载
            </n-button>
          </n-input-group>
        </n-flex>
      </n-gi>
      <n-gi>
        <n-flex class="max-w-[240px] ml-auto">
          <n-tree-select :options="options" placeholder="请选择要加载的地图矩阵集合" v-model:value="selectedValue" @update:value="handleUpdateValue" check-strategy="child" />
        </n-flex>
      </n-gi>
    </n-grid>
  </n-card>
  <n-card :style="{ height: `${computedHeight}px` }" class="flex-1 mt-2">
    <div id="olMap_wmts" class="absolute-full"></div>
    <Loading v-if="addLoading" />
  </n-card>
</template>
